<script setup>
import { onMounted, ref } from 'vue'
import { MotionComponent } from '@vueuse/motion'
import AntdIcon from '@/components/AntdIcon/index.vue'
import AddBanner from './components/AddBanner.vue'
import { bannerListApi, deleteBannerApi } from '@/service'
import { message, Modal } from 'ant-design-vue'

const addBannerRef = ref()
const bannerList = ref([])

const getBannerList = () => {
  bannerListApi().then((res) => {
    bannerList.value = res.items
  })
}

const addBannerSuccess = () => {
  getBannerList()
}

// 删除轮播图
const delBanner = (id, index) => {
  Modal.confirm({
    title: '删除轮播图',
    content: '确认删除该轮播图吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      deleteBannerApi({ carousel_id: id }).then(() => {
        bannerList.value.splice(index, 1)
        message.success('删除成功')
      })
    },
  })
}
// 显示添加弹窗
const showAddBanner = (type, record) => {
  if (type === 'add') {
    addBannerRef.value.open()
  } else {
    const { carousel_url, carousel_title, carousel_link, id } = record
    addBannerRef.value.open({ carousel_url, carousel_title, carousel_link, id })
  }
}

onMounted(() => {
  getBannerList()
})
</script>
<template>
  <div class="flex flex-col gap-5">
    <a-card :bordered="false">
      <a-button type="primary" @click="showAddBanner('add')">添加轮播图</a-button>
    </a-card>
    <MotionComponent preset="slideVisibleOnceRight">
      <a-card :bordered="false">
        <a-table :data-source="bannerList" :pagination="false" bordered>
          <a-table-column key="id" title="#" data-index="id" />
          <a-table-column key="carousel_title" title="轮播图标题" data-index="carousel_title" />
          <a-table-column key="carousel_url" title="轮播图" data-index="carousel_url">
            <template #default="{ text: carousel_url }">
              <a-image :src="carousel_url" :width="100" :height="60" />
            </template>
          </a-table-column>
          <a-table-column key="create_time" title="跳转地址" data-index="carousel_link" />
          <a-table-column key="create_time" title="创建时间" data-index="create_time" />
          <a-table-column key="action" title="操作">
            <template #default="{ record, index }">
              <div class="flex gap-5">
                <a-button type="primary" @click="showAddBanner('edit', record)">
                  <template #icon>
                    <AntdIcon icon="EditOutlined" />
                  </template>
                </a-button>
                <a-button type="primary" danger @click="delBanner(record.id, index)">
                  <template #icon>
                    <AntdIcon icon="DeleteOutlined" />
                  </template>
                </a-button>
              </div>
            </template>
          </a-table-column>
        </a-table>
      </a-card>
    </MotionComponent>
    <AddBanner ref="addBannerRef" @addBanner="addBannerSuccess" />
  </div>
</template>
